package com.application.module_chat2.presenter;

import com.application.module_chat2.bean.uibean.MessageBean;
import com.application.module_chat2.view.MessageView;
import com.application.mylibrary.base.mvp.IBasePresenter;
import com.application.mylibrary.im.IMMessageUtils;
import com.application.mylibrary.im.ImLocalResultbak;

import java.util.ArrayList;
import java.util.List;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;

/**
 * Created by lixuce on 2019/8/9.
 */
public class MessagePresenter extends IBasePresenter<MessageView> {
    private List<MessageBean> list;

    public MessagePresenter() {
        this.list = new ArrayList<>();
    }

    public void loadConversation() {
        list.clear();
        IMMessageUtils.getConversationList(new ImLocalResultbak<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> result) {

                MessageBean bean;
                for (Conversation conversation : result) {
                    MessageContent latestMessage = conversation.getLatestMessage();
                    bean = new MessageBean();
                    bean.messageReceiverTime = conversation.getSentTime();
                    bean.messageUId = conversation.getTargetId();
                    bean.messageUnRead = conversation.getUnreadMessageCount();
                    if (latestMessage instanceof TextMessage) {
                        UserInfo userInfo = latestMessage.getUserInfo();
                        if (userInfo != null) {
                            bean.messageHeadPic = userInfo.getPortraitUri().getPath();
                            bean.messageName = userInfo.getName();
                        }
                        bean.messageContent = ((TextMessage) latestMessage).getContent();
                    } else if (latestMessage instanceof VoiceMessage) {

                    }
                    list.add(bean);
                }
                if (getView() != null) {
                    getView().addConversationList(list);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode iErrorCode) {

            }
        });
    }

    public void handleMessage(Message message) {
        MessageBean bean = new MessageBean();
        bean.messageUId = message.getTargetId();
        if (getView() != null) {
            if (list.contains(bean)) {
                getView().upConversation(bean);
            } else {
                getView().addConversation(bean);
            }
        }
    }
}
